package com.itheima.controller;

import com.itheima.common.R;
import com.itheima.domain.ShoppingCart;
import com.itheima.service.ShoppingCartService;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * @author wuyiqiang
 * @2022/6/18 13:36
 */
@RestController
@RequestMapping(value = "/shoppingCart", produces = "application/json;charset=utf-8")
public class ShoppingCartController {

    @Autowired
    private ShoppingCartService shoppingCartService;
    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 购物车列表
     *
     * @return
     */
    @GetMapping("/list")
    public R select() {
        List<ShoppingCart> select = shoppingCartService.select();
        return R.success(select);
    }

    /**
     * 添加购物车
     *
     * @param shoppingCart
     * @return
     */
    @PostMapping("/add")
    public R add(@RequestBody ShoppingCart shoppingCart, HttpServletRequest request) {
        String userPhone = tokenToUsername(request);
        System.out.println(userPhone + "=====================debug");
        shoppingCart.setUserId(userPhone);
        return shoppingCartService.add(shoppingCart);
    }

    /**
     * 清空购物车
     *
     * @param request
     * @return
     */
    @DeleteMapping("/clean")
    public R clean(HttpServletRequest request) {
        String userId = tokenToUsername(request);
        shoppingCartService.delete(userId);
        return R.success("清空购物车成功");
    }

    /**
     * 删除套餐或者菜品
     * @return
     */
    @PostMapping("/sub")
    public R delete(@RequestBody ShoppingCart shoppingCart,HttpServletRequest request) {
        shoppingCartService.deleteById(shoppingCart,request);
        return R.success("删除成功");
    }


    /**
     * 利用token获得当前页面用户名
     *
     * @param request
     * @return
     */
    public String tokenToUsername(HttpServletRequest request) {
        //用户id设置
        String token = request.getHeader("AuthorizationUser");

        String username = (String) redisTemplate.opsForValue().get(token);


        return username;
    }
}
